import { ref } from 'vue'
import { onReady } from '@dcloudio/uni-app'
import http from '@/utils/request.js'
import { getApplyInfo, getApplyEnterprise } from '@/api'
import { useI18n } from 'vue-i18n'

export const TOKEN = ref(uni.getStorageSync('token'))

/**
 * 用户 hooks
 */
export const useUser = () => {
  const { t } = useI18n()
  const onBack = () => {
    uni.navigateBack()
  }

  /**
   * 获取用户信息
   */
  const getUserInfo = async () => {
    const res = await http.get('/api/userInfo')
    return res
  }

  /**
   * 登录
   */
  const login = async (formData) => {
    const res = await http.post('/api/login', formData)
    // uni.setStorageSync('token', res.token);

    uni.setStorage({
      key: 'token',
      data: res.token
    })
    TOKEN.value = res.token
    uni.showToast({
      title: t('login.success'),
      icon: 'success',
      mask: true,
      success: () => {
        setTimeout(() => {
          // onBack()
          uni.redirectTo({
            url: '/pages/index/index'
          })
        }, 1500)
      }
    })
  }

  /**
   * 退出登录
   */
  const logout = async () => {
    await http.get('/api/mobile/out')
    uni.removeStorageSync('token')
    TOKEN.value = ''
    uni.showToast({
      title: t('logout.success'),
      icon: 'success',
      mask: true
    })
  }

  /**
   * 判断是否需要登录然后再跳转到对应的贷款功能
   * @param {*} type enterprise：是企业贷款，为空则为个人贷款
   * @returns
   */
  const needLogin = async (type) => {
    if (!TOKEN.value) {
      uni.reLaunch({
        url: '/pages/login/login'
      })
      return
    }

    const isShow = type === 'enterprise'
    const res = isShow ? await getApplyEnterprise() : await getApplyInfo()
    // 待提交材料
    if ([1, 3, 4, 6, 8, 9, 10, 11, 13, 15, 16, 17].includes(res.status)) {
      uni.navigateTo({
        url: `/pages/success-page/success-page?state=${res.status}${isShow ? '&type=enterprise' : ''
          }`
      })
      return false
    }
    return true
  }

  /** 根据传入的数字，变化为 500万韩元  1000万韩元  1亿韩元 */
  const formatKoreanWon = (num) => {
    if (num === 0) return '0원';

    const units = [
      { value: 1000000000000, name: '조' },   // 10^12
      { value: 100000000, name: '억' },       // 10^8
      { value: 10000, name: '만' },           // 10^4
      { value: 1, name: '' }                // 1
    ];

    let result = [];
    let remaining = num;

    for (let i = 0; i < units.length; i++) {
      const { value, name } = units[i];
      const count = Math.floor(remaining / value);
      remaining %= value;

      if (count > 0) {
        result.push(`${count}${name}`);
      }
    }
// 원
    return result.length > 0 ? result.join(' ') +  '원': '0원';

    // return
    // // 确保传入的是数字
    // const num = Number(amount);
    // if (isNaN(num)) {
    //   return '-';
    // }

    // if (num >= 100000000) {
    //   // 1亿韩元及以上，使用“亿”为单位
    //   const yi = Math.floor(num / 100000000);
    //   return `${yi}억원`;
    // } else if (num >= 10000) {
    //   // 1万到9999万韩元，使用“万”为单位
    //   const wan = Math.floor(num / 10000);
    //   return `${wan}만원`;
    // } else {
    //   // 小于1万，直接显示
    //   return `${num}원`;
    // }
  }

  /** 格式传入的数字 */
  const addCommas = (num) => {
    const integerPart = Math.trunc(num)
    return integerPart.toLocaleString('en-US') + ' 원'
  }

  return {
    onBack,
    login,
    logout,
    getUserInfo,
    needLogin,
    formatKoreanWon,
    addCommas
  }
}
